import re

from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
from users.models import User
from utils.myitsdangerous import encode_signature_openid, decode_signature_openid


class QQAuthURLView(View):
    def get(self, request):
        # 1, 实例化一个 oauth对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        # 2, 通过 oauth对象的  get_qq_url 方法获取一个 二维码扫描地址
        login_url = oauth.get_qq_url()

        return redirect(login_url)


class OauthCallBackView(View):
    def get(self, request):
        # 1, 初始化数据
        code = request.GET.get('code')

        if not code:
            return http.HttpResponseForbidden('code丢失了!')

        # 2, 处理业务逻辑
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        access_token = oauth.get_access_token(code)
        openid = oauth.get_open_id(access_token)

        # 2,2 查询是否绑定过
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)

        except Exception as e:
            # 没有绑定过
            openid = encode_signature_openid(openid)
            return render(request, 'oauth_callback.html', {'openid': openid})

        # 如果绑定过了, 取用户 user
        user = oauth_user.user

        login(request, user)

        # 3, 返回响应
        response = redirect('/')
        response.set_cookie('username', user.username)

        return response

    def post(self, request):
        # 处理用户绑定业务
        # 1, 初始化数据, 手机号, 密码 , 短信验证码, openid
        openid = request.POST.get('openid')
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')

        if not all([openid, mobile, pwd, sms_code]):
            return http.HttpResponseForbidden('参数不全')

        # 1,3 校验密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden('密码格式有误')

        # 1,5 校验手机号
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式不正确')

        # 1,6 校验短信验证码
        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile)
        if redis_sms_code:
            redis_sms_code = redis_sms_code.decode()
        if sms_code != redis_sms_code:
            return http.HttpResponseForbidden('短信验证码错误')
        # 1,7 校验openid
        openid = decode_signature_openid(openid)
        if not openid:
            return http.HttpResponseForbidden('openid 已失效')

        # 2, 处理业务逻辑, 绑定用户, 并登录用户
        # 2,1 判断此手机号, 是否已经注册美多用户
        # 如果已经注册, 就直接绑定,
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 如果没有注册, 就生成一个新用户, 再绑定, 新用户的用户名使用手机号
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)


        OAuthQQUser.objects.create(user=user, openid=openid)

        login(request, user)
        response = redirect('/')
        response.set_cookie('username', user.username)

        return response
